package cn.dapeng.thread.delayedQueue;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.thread.delayedQueue
 * @Description TODO
 * @ClassName MyAbstractQueue
 * @Author xupenghong
 * @Date 2024/8/28 14:14
 * @Version 1.0.0
 */
public abstract class MyAbstractQueue<E> implements MyQueue<E> {

    private final RingArray<E> array;
    private final int capacity;

    private final ReentrantLock lock = new ReentrantLock();

    public MyAbstractQueue(int capacity) {
        this.capacity = capacity;
        array = new RingArray<>(capacity);
    }

    public RingArray<E> getArray() {
        return array;
    }

    public ReentrantLock getLock() {
        return lock;
    }

    public int getCapacity() {
        return capacity;
    }

    @Override
    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return array.peek();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void clear() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            array.clear();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public boolean isEmpty() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return getSize() == 0;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public int getSize() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return array.getSize();
        } finally {
            lock.unlock();
        }
    }

}
